package com.qf.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * projectName:
 * author:luo
 * time:2023/1/6 9:29
 * description:
 */
public class BaseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String methodName = request.getParameter("method");
        try {
            Method method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            if (method != null) {
                //反射获取有返回值方法处理返回值
                String url =(String) method.invoke(this, request, response);//redirect:/index.jsp
                if (url == null||url.trim().length()==0) {
                    return;
                }
//                System.out.println("url = " + url);
                //转发重定向
                if(url.startsWith("redirect:")){//重定向
                    String redirectURL = url.substring(url.indexOf(":") + 1);//  /index.jsp
                    response.sendRedirect(request.getContextPath()+redirectURL);
                }else{//转发  /registerSuccess.jsp
                    request.getRequestDispatcher(url).forward(request,response);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
